<!--
 * @Author: 2112778581 2112778581@qq.com
 * @Date: 2023-10-17 11:51:52
 * @LastEditors: fengshan525 2735332396@qq.com
 * @LastEditTime: 2025-09-21 15:39:50
 * @FilePath: \cra-front\src\views\product\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <el-form inline>
      <el-form-item label="标题">
        <el-input clearable placeholder="请输入标题" v-model="search.title"></el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-cascader style="width: 300px" v-model="categoryArr" :options="caList" :props="props" @change="handleCascaderChange" placeholder="请选择分类" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="refresh" size="small">
          <el-icon>
            <Refresh />
          </el-icon>
          重置</el-button
        >
        <el-button type="primary" @click="load" size="small">
          <el-icon>
            <Search />
          </el-icon>
          搜索</el-button
        >
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon style="vertical-align: middle">
            <Plus />
          </el-icon>
          <span style="vertical-align: middle"> 新增 </span>
        </el-button>
        <el-button @click="$router.go(-1)" size="small">
          <el-icon>
            <ArrowLeft />
          </el-icon>
          返回
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" border>
      <el-table-column align="center" label="序号" type="index" width="55" fixed="left" />
      <el-table-column align="center" label="排序" prop="sort" width="55" />
      <el-table-column align="center" label="标题" prop="title" width="140"/>
      <el-table-column align="center" label="主图" width="140">
        <template v-slot="{ row }">
          <el-image :preview-teleported="true" fit="cover" style="width: 100px; height: 100px" :src="row.mainImages[0]" :preview-src-list="row.mainImages"></el-image>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" label="描述" prop="description" />
      <el-table-column align="center" label="分类" prop="categoryName" />
      <el-table-column align="center" label="标签" prop="tags">
        <template v-slot="{ row }">
          <div v-if="row.tags.length > 0">
            <el-tag style="margin: 5px" v-for="(item, idx) in row.tags" :key="idx">{{ item.name }}</el-tag>
          </div>
          <div v-else>没有标签</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否发布" prop="tags">
        <template v-slot="{ row }">
          <el-switch v-model="row.isPublished" @change="handleSwitchChange(row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否推荐" prop="tags">
        <template v-slot="{ row }">
          <el-switch v-model="row.isRecommend" @change="handleSwitchChange(row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否置顶" prop="isTop">
        <template v-slot="{ row }">
          <el-switch v-model="row.isTop" @change="handleSwitchChange(row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="型号" prop="modelType" />
      <!--      <el-table-column align="center" width="200" label="使用说明书" prop="instruction" />-->
      <el-table-column align="center" label="创建时间" prop="createdAt">
        <template v-slot="{ row }">
          {{ dayjs(row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" fixed="right" align="center">
        <template v-slot="{ row }">
          <el-button size="small" @click="editProduct(row)" type="primary" text>编辑</el-button>
          <el-button size="small" type="danger" text @click="delProduct(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="pages.total" v-model:pageNum="pages.pageNum" v-model:pageSize="pages.pageSize" @change="load" style="margin-top: 10px"></Pagination>
  </div>
</template>

<script setup lang="ts">
import { getProjectList, editProjectApi, addProjectApi, delProjectApi } from "@/api/content/project";
import { getModuleById } from "@/api/webbase";
import { getMenusByModelId } from "@/api/webmenus";
import { buildTreeData } from "@/utils/tools";
import { getAllWebMenuByModelType } from "@/api/webmenus/index";

// @ts-ignore
import Pagination from "@/components/Pagination/index.vue";
import dayjs from "dayjs";
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { Refresh } from "@element-plus/icons-vue";
const route = useRoute();
const modelItem = ref<any>({});
const moduleId = route.query.moduleId as string;
const selectedCategory = ref<string>("");

const list = ref([]);
const search = ref({
  title: ""
});
const pages = reactive({
  pageSize: 20,
  pageNum: 1,
  total: 0
});

// 级联选择器相关变量
const categoryArr = ref([]);
const caList = ref([]);
const props = {
  value: "value",
  label: "label",
  children: "children",
  checkStrictly: true
};
const router = useRouter();

/**
 * 新增项目
 */
const handleAdd = () => {
  router.push({ path: "/project-add", query: { moduleId, moduleName: encodeURIComponent(modelItem.value.moduleName) } });
};

const delProduct = (row: any) => {
  ElMessageBox.confirm("删除后不可恢复，是否确认删除?", "确认删除", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning"
  })
    .then(() => {
      delProjectApi(row._id).then((res) => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        load();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const refresh = () => {
  search.value.title = "";
  selectedCategory.value = "";
  categoryArr.value = [];
  load();
};

/**
 * 处理级联选择器变化事件
 * @param value 选中的值数组
 */
const handleCascaderChange = (value: any[]) => {
  // categoryArr.value = value;
  selectedCategory.value = value[value.length - 1];
  load();
};

/**
 * 加载分类列表数据
 * 获取分类数据并构建树形结构
 */
const loadCateList = () => {
  getAllWebMenuByModelType("category", 1)
    .then((res) => {
      const rawData = (res.data || res) as any[];
      // 保存原始平铺数据
      // rawCategoryData.value = rawData;
      // 将平铺数据转换为树形结构
      caList.value = buildTreeData(rawData);
    })
    .catch((error) => {
      console.error("获取分类列表失败:", error);
      ElMessage.error("获取分类列表失败");
    });
};

const load = async () => {
  const res = await getModuleById(moduleId);
  modelItem.value = res.data;
  getProjectList({
    title: search.value.title,
    moduleId: moduleId,
    categoryId: selectedCategory.value,
    pageSize: pages.pageSize,
    pageNum: pages.pageNum
  }).then((res) => {
    list.value = res.data.rows;
    pages.total = res.data.total;
  });

  getMenusByModelId(moduleId)
    .then((res) => {
      console.log("res", res);
      // @ts-ignore
      if (res.data && res.data.length > 0) {
        // @ts-ignore 使用公共函数构建树形数据
        caList.value = buildTreeData(res.data);
        console.log("构建的树形数据:", caList.value);
      }
    })
    .catch((error) => {
      console.error("获取菜单数据失败:", error);
    });

  loadCateList();
};

const editProduct = (row: any) => {
  // console.log('row', row);
  router.push(`/project-add?pId=${row._id}&moduleId=${route.query.moduleId}&moduleName=${encodeURIComponent(modelItem.value.moduleName)}`);
};

const handleSwitchChange = (row) => {
  editProjectApi(row._id, row).then((res) => {
    if (res.status === 200) {
      ElMessage({
        type: "success",
        message: "操作成功"
      });
      load();
    }
  });
};

load();
</script>

<style scoped lang="less"></style>
